import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:mobile_scanner/mobile_scanner.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';
import 'package:ws_group_chat/pages/client/client_wait_page.dart';
import 'package:ws_group_chat/provider/client_data.dart';

class ScanPage extends StatefulWidget {
  const ScanPage({super.key});

  @override
  State<ScanPage> createState() => _ScanPageState();
}

class _ScanPageState extends State<ScanPage> {
  MobileScannerController controller = MobileScannerController();
  bool hasPermission = false;
  bool isScanning = true;
  @override
  void initState() {
    super.initState();
    _checkPermission();
  }

  Future<void> _checkPermission() async {
    final status = await Permission.camera.request();
    setState(() {
      hasPermission = status.isGranted;
    });
  }

  void _onDetect(BarcodeCapture capture) async {
    if (!isScanning) return;
    final Barcode barcode = capture.barcodes[0];
    if (barcode.rawValue != null) {
      print(barcode.rawValue);
      if (barcode.rawValue!.contains('ws://')) {
        isScanning = false;
        context.read<ClientData>().wsUrl = barcode.rawValue;
        await EasyLoading.show(status: '连接服务器...');
        bool isConnected = await context.read<ClientData>().connectToServer();
        if (isConnected) {
          EasyLoading.dismiss();
          EasyLoading.showSuccess('连接服务器成功');
          Navigator.pushReplacement(
            context,
            MaterialPageRoute(builder: (context) => const ClientWaitPage()),
          );
        } else {
          EasyLoading.showError('连接服务器失败');
          return;
        }
      } else {
        EasyLoading.showError('无效的二维码');
      }
    }
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: hasPermission
          ? MobileScanner(controller: controller, onDetect: _onDetect)
          : const SizedBox(),
    );
  }
}
